import * as fs from 'node:fs/promises';
import { Uri } from "vscode";
import { DataType, TreeData } from "../ApiTreeDataProvider";
import { fetchApiList } from '../cmd/fetchApiList';
import { Memory } from '../memory';

export namespace AnyChecker {

  export function apiTreeData<K extends DataType = DataType>(d: any, k: K): d is TreeData<K> {
    return d instanceof TreeData && d.type === k;
  }

  export function uri(d: any): Uri | undefined {
    return d instanceof Uri ? d : undefined;
  }

  export async function apiFileUri(d: any): Promise<{ uri: Uri, doc: Memory.IDoc } | undefined> {
    const r = uri(d);
    if (r?.scheme !== 'file') { return; }

    const filePath = r.fsPath;
    const content = await fs.readFile(filePath).then(v => v.toString()).catch(e => console.log(e));

    if (!content?.match(/\/\/\/\/ Generated by Torna Api [Visitor|Stealer]/)) {
      return;
    }
    if (!Memory.fullDocList.length) {
      await fetchApiList();
    }
    const regResult = content?.match(/\/\/\/\/\s*@docId\s*(\S*)\n?/);
    if (!regResult || typeof regResult[1] !== 'string') { return; }
    const docId = regResult[1];
    const doc = Memory.fullDocList.find(v => v.id === docId);

    if (!doc) { return; }
    return { uri: r, doc };
  }


}